#include <iostream>
#include <fstream>

#include <Inventor/Qt/SoQt.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoCoordinate3.h>
#include <Inventor/nodes/SoLineSet.h>
#include <Inventor/nodes/SoBaseColor.h>

#include <QFileDialog>

#define GLOBALS_HERE
#include "scenegraph.hpp"
#include "mainwin.hpp"
#include "face_cutter_trace_dialog.hpp"

#include "simulationwin.hpp"



MainWindow::MainWindow(QWidget *parent):QMainWindow(parent)
{
    setupUi(this);
    SoQt::init(this);

    scenegraph::root=new SoSeparator;
    scenegraph::root->ref();

    scenegraph::viewer=new SoQtExaminerViewer(this->viewplace);
    scenegraph::viewer->setDecoration(false);
    scenegraph::viewer->setSceneGraph( scenegraph::root);
}

MainWindow::~MainWindow()
{
    delete scenegraph::viewer;
    scenegraph::root->unref();
}

void MainWindow::on_actionBuildFaceCutterTrace_activated()
{

    face_cutter_trace_dialog *win= new face_cutter_trace_dialog;

    win->show();
}

void MainWindow::on_actionSimulate_activated()
{
    simulationwin *win= new simulationwin;
    win ->show();
      win->prepare();

}
void MainWindow::on_actionSaveTrace_activated()
{

    if (!model::path.size()) return;

    QString filename = QFileDialog::getSaveFileName(this, tr("select file to save trace"),
						    "",
						    tr("*.trace"));
	
    if(filename.isEmpty())
      return;
		
    ofstream of(filename.toAscii().constData());

    if(!of)
      return;
    

    of<<model::tooldiam<<endl;
    for (int i=0; i<model::path.size(); i++)
    {
        point &p=model::path[i];
        of<<p.x<<" "<<p.y<<" "<<p.z<<" "<<p.o<<" "<<p.a<<" "<<p.t<<endl;
    }
}

void MainWindow::on_actionOpenTrace_activated()
{
  QString filename = QFileDialog::getOpenFileName(this, tr("Open trace file"),
						    "",
						  tr("*.trace"));
	
  if(filename.isEmpty())
    return;

  
  ifstream f(filename.toAscii().constData());

  if(!f)
    return;
  

  f>>model::tooldiam;
    while (!f.eof())
    {
      double x,y,z,o,a,t;
        f>>x;
        f>>y;
        f>>z;
	f>>o;
        f>>a;
        f>>t;
	
        model::path.push_back(point(x,y,z,o,a,t));
    }
    
    static SoSeparator *trace=NULL;

    if (trace==NULL)
    {
        trace=new SoSeparator;
        trace->ref();
    }
    else
    {
        trace->removeAllChildren();
    }

    SoCoordinate3 *coords=new SoCoordinate3;
    SoLineSet *tra=new SoLineSet;

    SoBaseColor * tcol = new SoBaseColor;
    tcol->rgb = SbColor(1,0,1);

    trace->addChild(tcol);

    trace->addChild(coords);
    trace->addChild(tra);

    cout<<"---\n";
    long n=0;
    for (int i=0; i<model::path.size(); i++)
      {
	point p=model::path[i];
	coords->point.set1Value(n++,p);
	if(i%10==0)
	  {
	    point normal=p+point_dir(p)*4;
	    coords->point.set1Value(n++,normal);
	    coords->point.set1Value(n++,p);
	  }
      }
    

    tra->numVertices.set1Value(0,n);

    cerr<<endl;

    scenegraph::root->addChild(trace);
}
